// 导入 mongoose 模块
const mongoose = require("mongoose");

// 创建连接
mongoose.connect("mongodb://127.0.0.1:27017/bilibili");

// 回调设置
mongoose.connection.once("open", () => {
  // 创建文档结构
  let novelSchema = new mongoose.Schema({
    name: String,
    author: String,
    price: Number,
    is_hot: Boolean,
  });

  // 创建文档结构对象
  let novelModel = mongoose.model("novel", novelSchema);

  // 条件查找
  /* novelModel.find(
    {
      price: { $lt: 20 },
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  ); */

  // 逻辑或查找
  /* novelModel.find(
    {
      $or: [
        {
          author: "甲鱼不是龟",
        },
        {
          author: "游泳的猫",
        },
      ],
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  ); */

  // 逻辑与查找
  /* novelModel.find(
    {
      $and: [
        {
          price: {
            $gt: 5,
          },
        },
        {
          price: {
            $lt: 20,
          },
        },
      ],
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  ); */

  // 正则匹配
  /* novelModel.find(
    {
      name: /游/,
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  ); */

  // 正则另外的表达方式
  novelModel.find(
    {
      name: new RegExp("游"),
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  );

  console.log("连接成功");
});

mongoose.connection.on("error", () => {
  console.log("连接失败");
});

mongoose.connection.on("close", () => {
  console.log("连接关闭");
});
